package com.mc.lp.database.dao.impl;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import com.mc.lp.database.dao.IMicroCampusEntityDAO;
import com.mc.lp.database.entity.MicroCampusEntity;
import com.mc.lp.database.service.handler.constant.SearchParam;

/*
 * @author aphanda
 * @date Dec 24, 2014
 * @time 3:09:51 PM
 */
@Repository
public class MicroCampusEntityDAOImpl extends
		AbstractGenericHibernateDAO<MicroCampusEntity, Long, IMicroCampusEntityDAO> implements	IMicroCampusEntityDAO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Set<MicroCampusEntity> getChildsByParentId(Long parentId) {

// used Set here to counter Hibernate Duplicates in eager loading
		Set<MicroCampusEntity> childList = new HashSet<MicroCampusEntity>();

		MicroCampusEntity parentObj = new MicroCampusEntity();
		Criteria crit = this.getCurrentSession().createCriteria(MicroCampusEntity.class);
		crit.add(Restrictions.eq("user.id", parentId));
		parentObj = (MicroCampusEntity) crit.uniqueResult();
		if(parentObj==null){
			return childList;
		}

		Criteria listCrit = this.getCurrentSession().createCriteria(MicroCampusEntity.class);
		listCrit.add(Restrictions.eq("parentEntityId", parentObj.getId()));
		childList.addAll(listCrit.list());
		return childList;
	}

	

	@Override
	public Set<MicroCampusEntity> getEntitiesBySearchParam(SearchParam searchParam,
			String searchValue) throws DataAccessException {
		Criteria crit = this.getCurrentSession().createCriteria(MicroCampusEntity.class);
		Set<MicroCampusEntity> studentList = new HashSet<MicroCampusEntity>();
		if(!searchParam.equals(SearchParam.USER_ID))
			crit.add(Restrictions.isNotNull("parentEntityId"));
		
		switch (searchParam) {
		case REGISTRATION_ID:
			crit.add(Restrictions.like("registration.id", NumberUtils.toLong((searchValue))));
			break;
		case MOBILE_NUMBER:
			crit.createAlias("contacts", "contact");
			//crit.add(Restrictions.eq("contact.contactTypeId", ContactType.getType(0)));
			crit.add(Restrictions.like("contact.contactValue", searchValue, MatchMode.ANYWHERE));
			break;
		case EMAIL_ADDRESS:
			crit.add(Restrictions.like("primaryEmail", searchValue, MatchMode.ANYWHERE));
			break;
		case FIRST_NAME:
			crit.add(Restrictions.like("firstName", searchValue, MatchMode.ANYWHERE));
			break;
		case LAST_NAME:
			crit.add(Restrictions.like("lastName", searchValue, MatchMode.ANYWHERE));
			break;
		case USER_ID:
			crit.add(Restrictions.like("user.id",NumberUtils.toLong(searchValue)));
			break;

		default:
			break;
		}
		
		studentList = new HashSet<MicroCampusEntity>(crit.list());
		return studentList;
	}
}